<!-- Good be like is a Requirement Statistics Project table -->
<template>
  <DialogLayout ref="dialogRef" method="POST" dialog-width="800px" path="/dev-api/oa/headcount" @submited="handlerDialogSubmited">
    <el-form-item label="项目">
      <el-select disabled v-model="form.projectId" placeholder="请选择项目" style="width: 100%"> <el-option v-for="item in projectList" :key="item.code" :label="`${item.code}-${item.cname}`" :value="item.id" /> </el-select>
    </el-form-item>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="工序">
          <el-input v-model="form.processName" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="时间段" prop="timeSlot">
          <el-date-picker disabled v-model="form.timeSlot" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="计划" prop="weekPlanNum">
          <el-input v-model="form.weekPlanNum" style="width: 100px" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="实际" prop="weekFinishNum">
          <el-input v-model="form.weekFinishNum" style="width: 100px" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="计划内容" prop="weekPlanRemark">
          <el-input v-model="form.weekPlanRemark" type="textarea" :rows="4" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="完成内容" prop="weekFinishRemark">
          <el-input v-model="form.weekFinishRemark" type="textarea" :rows="4" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="本周进度说明" prop="weekRemark">
          <el-input v-model="form.weekRemark" type="textarea" :rows="4" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="本月进度说明" prop="monthRemark">
          <el-input v-model="form.monthRemark" type="textarea" :rows="4" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="单月计划" prop="monthPlanRemark">
          <el-input v-model="form.monthPlanRemark" type="textarea" :rows="4" />
        </el-form-item>
      </el-col>
      <el-col :span="12"> </el-col>
    </el-row>
    <template #footer>
      <el-button v-if="form.colId" type="danger" @click="handleClickBtnDelete">删除</el-button>
    </template>
  </DialogLayout>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import DialogLayout from '../../layout/DialogLayout.vue'
import { FormRules } from 'element-plus'
import { useUsersStore, useProjectssStore } from '../../stores'
import { formatDate } from '../../utils'
import Api from '../../api'
import { ElMessage, ElMessageBox } from 'element-plus'

const emits = defineEmits(['submited'])
// const deptProps = ref({ label: 'deptName', value: 'deptId' })
// const deptList = ref(useDeptStore().getAllState())
const dialogRef = ref<InstanceType<typeof DialogLayout>>()
const projectssStore = useProjectssStore()
const projectList = ref<Array<{ id: number; code: string; cname: string }>>(projectssStore.getAllState() as any)
// const weeks = ref<{ start: Date; end: Date }[]>([])
const startDate = ref('')
const endDate = ref('')
const form = reactive({
  id: null,
  colId: -1,
  projectId: 0,
  processId: 0,
  processName: '',
  projectCode: '',
  projectName: '',
  weekStartDate: '',
  weekEndDate: '',
  deptIds: [] as number[],
  deptId: -1,
  deptName: '',
  userNum: 0,
  weekPlanNum: null,
  weekFinishNum: null,
  weekPlanRemark: '',
  weekFinishRemark: '',
  weekRemark: '',
  monthRemark: '',
  monthPlanRemark: '',
  createBy: useUsersStore().user.username,
  timeSlot: [] as Date[],
})
/**
 * 验证时间区间是否被占用
 *
 * @param rule 校验规则
 * @param value 校验值，应为包含两个时间戳的数组 [startTime, endTime]
 * @param callback 回调函数，验证通过时传入null，验证失败时传入错误信息
 */
const validateTimeSlot = (_: any, value: any, callback: any) => {
  //   weekStartDate.value = formatDate(value[0], 'yyyy-MM-dd')

  // weekEndDate.value = formatDate(value[1], 'yyyy-MM-dd')
  // console.log('startDate', startDate.value)
  // console.log('endDate', endDate.value)

  if (!value[0] && !value[1]) {
    callback(new Error('请选择时间段'))
  } else if (new Date(startDate.value).getTime() > new Date(value[0]).getTime() || new Date(endDate.value).getTime() < new Date(value[1]).getTime()) {
    callback(new Error(`时间区间必须在 ${formatDate(new Date(startDate.value), 'yyyy-MM-dd')} 到 ${endDate.value} 之间`))
  } else {
    callback()
  }
}

/**
 * 验证时间区间是否被占用
 *
 * @param rule 校验规则
 * @param value 校验值，应为包含两个时间戳的数组 [startTime, endTime]
 * @param callback 回调函数，验证通过时传入null，验证失败时传入错误信息
 */
const validateDept = (_: any, value: any, callback: any) => {
  // console.log('rule', rule)

  if (value.length < 3) {
    callback(new Error('请选择部门'))
  } else {
    callback()
  }
}
const validateWeekPlanNum = (_: any, value: any, callback: any) => {
  if (value === '' || value === null || /^[0-9]+$/.test(value)) {
    callback()
  } else {
    callback(new Error('只能输入正整数或留空'))
  }
}
const validateWeekFinishNum = (_: any, value: any, callback: any) => {
  console.log('validateWeekFinishNum value', value)
  if (value === '' || value === null || /^[0-9]+$/.test(value)) {
    callback()
  } else {
    callback(new Error('只能输入正整数或留空'))
  }
}

const rules = reactive<FormRules>({
  timeSlot: [{ required: true, validator: validateTimeSlot, trigger: ['change', 'blur'] }],
  deptIds: [{ required: true, validator: validateDept, trigger: ['change', 'blur'] }],
  userNum: [
    {
      required: true,
      validator: (rule: any, value: number, callback: any) => {
        if (rule) {
        }
        if (value < 0) {
          callback(new Error('人数必须大于 0'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  weekPlanNum: [{ validator: validateWeekPlanNum, trigger: 'blur' }],
  weekFinishNum: [{ validator: validateWeekFinishNum, trigger: 'blur' }],
})

const openDialog = (val: any) => {
  const { weekStartDate, weekEndDate, processId, processName, projectId, projectCode, projectName, colId, weekPlanNum, weekFinishNum, weekPlanRemark, weekFinishRemark, weekRemark, monthRemark, monthPlanRemark } = val

  startDate.value = weekStartDate
  endDate.value = weekEndDate

  form.colId = colId
  form.processId = processId
  form.processName = processName
  form.weekPlanNum = weekPlanNum
  form.weekFinishNum = weekFinishNum
  form.projectId = projectId
  form.projectCode = projectCode
  form.projectName = projectName
  form.weekPlanRemark = weekPlanRemark
  form.weekFinishRemark = weekFinishRemark
  form.weekRemark = weekRemark
  form.monthRemark = monthRemark
  form.monthPlanRemark = monthPlanRemark
  // form.deptIds = [...arrFromA, deptId]
  form.timeSlot = [weekStartDate, weekEndDate]
  // form.userNum = userNum
  const submitFunction = colId ? updateRequirement : addRequirement
  dialogRef.value?.openDialog({
    title: '编辑项目计划',
    class: 'dialog-add-headcount',
    form: form,
    rules: rules,
    submitFunction,
  })
}

/**
 * 异步更新需求
 *
 * @param callback - 回调函数，当操作完成后调用
 */
const updateRequirement = async (callback: Function) => {
  const { code } = await Api.InformationRequirement.updateById({
    id: form.colId,
    weekPlanNum: form.weekPlanNum,
    weekFinishNum: form.weekFinishNum,
    weekPlanRemark: form.weekPlanRemark,
    weekFinishRemark: form.weekFinishRemark,
    weekRemark: form.weekRemark,
    monthRemark: form.monthRemark,
    monthPlanRemark: form.monthPlanRemark,
  })
  if (code === 200) {
    ElMessage({
      message: `修改成功！`,
      grouping: true,
      type: 'success',
    })
  } else {
    ElMessage({
      message: `修改失败！`,
      grouping: true,
      type: 'error',
    })
  }
  callback()
}

/**
 * 异步添加需求
 *
 * @param callback 回调函数，添加需求完成后执行
 * @returns 无返回值
 */
const addRequirement = async (callback: Function) => {
  const { code } = await Api.InformationRequirement.create({
    id: null,
    weekStartDate: formatDate(form.timeSlot[0], 'yyyy-MM-dd'),
    weekEndDate: formatDate(form.timeSlot[1], 'yyyy-MM-dd'),
    projectId: form.projectId,
    projectCode: form.projectCode,
    processId: form.processId,
    processName: form.processName,
    weekPlanNum: form.weekPlanNum == '' ? null : form.weekPlanNum,
    weekFinishNum: form.weekFinishNum == '' ? null : form.weekFinishNum,
    weekPlanRemark: form.weekPlanRemark,
    weekFinishRemark: form.weekFinishRemark,
    weekRemark: form.weekRemark,
    monthRemark: form.monthRemark,
    monthPlanRemark: form.monthPlanRemark,
    createBy: form.createBy,
  })

  if (code === 200) {
    ElMessage({
      message: `添加成功！`,
      grouping: true,
      type: 'success',
    })
  } else {
    ElMessage({
      message: `添加失败！`,
      grouping: true,
      type: 'error',
    })
  }
  await callback()
}

const handlerDialogSubmited = (data: any) => {
  emits('submited', data)
}

const handleClickBtnDelete = async () => {
  ElMessageBox.confirm('确定要删除该条数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await Api.InformationRequirement.deleteById([form.colId])

      ElMessage({
        message: `删除成功！`,
        grouping: true,
        type: 'success',
      })
      emits('submited')
      dialogRef.value?.closeDialog()
    })
    .catch(() => {})
}

defineExpose({
  openDialog,
})
</script>
<style lang="scss" scoped></style>
